using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using EstimateTracker.DataAccess.Repositories;
using JetBrains.Annotations;
using Microsoft.Practices.Prism.Commands;

namespace EstimateTracker.ViewModels
{
    public class ReportSummaryViewModel : ViewModelBase
    {
        private readonly ITaskRepository _taskRepository;
        private DateTime _selectedDate;
        private DailySummary _selectedItem;

        public ReportSummaryViewModel([NotNull] ITaskRepository taskRepository)
        {
            if (taskRepository == null) throw new ArgumentNullException("taskRepository");
            _taskRepository = taskRepository;

            DailySummaries = new ObservableCollection<DailySummary>();
            SelectedDate = DateTime.Now;
        }

        public ObservableCollection<DailySummary> DailySummaries { get; set; }

        public ICommand Search
        {
            get
            {
                return new DelegateCommand
                (
                    () =>
                    {
                        IEnumerable<object[]> findActualsForDay = _taskRepository.FindActualsForDay(SelectedDate).ToList();
                        DailySummaries.Clear();
                        findActualsForDay.ToList().ForEach
                        (
                            BuildDailySummary
                        );
                    }
                );
            }
        }

        private void BuildDailySummary(object[] obj)
        {
            DailySummaries.Add
            (
                new DailySummary
                (
                     obj[0].ToString(),
                     obj[1].ToString(),
                     obj[2].ToString(),
                     Convert.ToDouble(obj[3]),
                     Convert.ToDouble(obj[4])
                )
            );
        }

        public DateTime SelectedDate
        {
            get { return _selectedDate; }
            set
            {
                _selectedDate = value;
                OnPropertyChanged("SelectedDate");
            }
        }

        public DailySummary SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                _selectedItem = value;
                OnPropertyChanged("SelectedItem");
            }
        }
    }
}